/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ${USER}
 * Date: ${YEAR}-${MONTH}-${DAY}
 * Time: ${TIME}
 */
public class HashBuck {
    static class Node{
        public int key;
        public int val;
        public Node next;
        public Node(int key, int val){
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array;
    public int usedSize;
    public static final double LOAD_FACTOR = 0.75;
    public HashBuck(){
        array = new Node[10];
    }
    public void push(int key, int val){
        int index = key % array.length; //除留余数法映射到下标
        Node cur = array[index];
        while(cur != null){ //找一下链表中是否已经存在key, 如果是就更新后直接返回
            if(cur.key == key){
                cur.key = key;
                return;
            }
            cur = cur.next;
        }
        Node node = new Node(key, val); //来到这里说明链表中不存在对应的节点
        //头插
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if(calaLoadFactor() >= LOAD_FACTOR){
            resize();
        }
    }
    public void resize(){
        Node[] tmp = new Node[2 * array.length];
        for(int i = 0; i < array.length; i++){
            Node cur = array[i];
            while(cur != null){
                int index = cur.key % tmp.length; //重新哈希到新数组的映射位置
                Node curNext = cur.next;
                cur.next = tmp[index];
                tmp[index] = cur;
                cur = curNext;
            }
        }
        array = tmp;
    }
    private double calaLoadFactor() {
        return usedSize * 1.0 / array.length;   //计算负载因子, 元素个树 / 数组长度
    }
    public int get(int key){
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}